// Problem: 
// Contest: 
// URL: 
// Memory Limit: 
// Time Limit: 
// #pragma GCC optimize("Ofast")
// #pragma GCC optimize("unroll-loops")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){
	int s=0,w=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
	while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
	return s*w;
}
signed main()
{
	int n,ans=0;
	cin>>n;
	vector<int> v(n+1);
	set<int> s;
	//s.insert(0);
	for(int i=1;i<=n;i++)
	{
		cin>>v[i];
		if(i==1)ans=v[i];
		else 
		{
			auto x=s.lower_bound(v[i]);
			if(x!=s.begin())
			{
				auto y=--s.lower_bound(v[i]);
				ans+=min(abs(*x-v[i]),abs(*y-v[i]));
			}
			else ans+=abs(*x-v[i]);
		}
		s.insert(v[i]);
	}
	cout<<ans;
	return 0;
}
